package com.linzm.leetcode.primary.exercises3_20230122;

import java.util.*;

/**
 * @Author zimingl
 * @Date 2023/1/23 20:02
 * @Description: 查找共用字符
 */
public class Demo7_1002 {
    /**
     * 给你一个字符串数组 words ，
     * 请你找出所有在 words 的每个字符串中都出现的共用字符（ 包括重复字符），并以数组形式返回。
     * 你可以按 任意顺序 返回答案。
     * 输入：words = ["bella","label","roller"]
     * 输出：["e","l","l"]
     *
     * 做法：取最小值，因为公用的一定有值，不共有的最小值最终就是0，把有值的输出就行了
     */
    public static void main(String[] args) {
        Demo7_1002 demo7_1002 = new Demo7_1002();
//        String[] words = {"cool", "lock", "cook"};
//        String[] words = {"acabcddd","bcbdbcbd","baddbadb","cbdddcac","aacbcccd","ccccddda","cababaab","addcaccd"};
        String[] words = {"bella", "label", "roller"};
        List<String> list = demo7_1002.commonChars(words);
        System.out.println(String.join(" ", list));
    }

    private List<String> commonChars(String[] words) {
        int[] arrMin = new int[26];
        Arrays.fill(arrMin, Integer.MAX_VALUE);
        for (int i = 0; i < words.length; i++) {
            int[] arr = new int[26];
            for (int j = 0; j < words[i].length(); j++) {
                arr[words[i].charAt(j) - 'a']++;
            }
            for (int j = 0; j < arrMin.length; j++) {
                arrMin[j] = Math.min(arrMin[j], arr[j]);
            }
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < arrMin.length; i++) {
            while (arrMin[i]-- > 0) {
                list.add(String.valueOf((char) (i+'a')));
            }
        }
        return list;
    }
}
